import { onMounted, ref } from 'vue'
import type { Ref, UnwrapRef } from 'vue'

interface DataParams<T> {
  defaultValue: T
  fetchData: () => Promise<any>
}

interface DataReturn<T> {
  data: Ref<UnwrapRef<T>>
  loading: Ref<boolean>
  refresh: () => Promise<void>
}

export const useFetchData = <T>({ defaultValue, fetchData }: DataParams<T>): DataReturn<T> => {
  const data = ref<T>(defaultValue)
  const loading = ref<boolean>(true)

  onMounted(async () => {
    await refresh()
  })

  const refresh = async () => {
    data.value = await fetchData()
    loading.value = false
  }

  return {
    data,
    loading,
    refresh
  }
}
